package cn.gson.school.controller.xitong;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gson.school.conmmon.JsonResult;
import cn.gson.school.dao.xitong.ResourcesDao;
import cn.gson.school.entity.xitong.ResourcesEntity;
import cn.gson.school.mappers.xitong.ResourceMapper;
import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
@Transactional(readOnly = true)
@RequestMapping("/resource/manager")
public class ResourcesController {

	@Autowired
	private ResourcesDao resDao;
	@Autowired
	private ResourceMapper resMapper;
	/**

	 * 权限管理主界面

	 * 

	 * @param model

	 * @return

	 */
	@GetMapping
	public String index() {
		return "xitong/resource_manager";
	}

	@RequestMapping("/list")
	@ResponseBody
	public List<ResourcesEntity> list() {

		List<ResourcesEntity> roots = resDao.findAllByParentIsNull();

		return roots;
	}

	@RequestMapping({ "/form", "/load" })
	public String form(Long id, Model model) {
		if (id != null) {
			// 编辑

			ResourcesEntity resources = resDao.findOne(id);
			model.addAttribute("resources", resources);
		}
		return "xitong/resources_form";
	}
	
	@PostMapping("/combo")
    @ResponseBody
    public List<ResourcesEntity> combo() {
        List<ResourcesEntity> roots = resDao.findAllByParentIsNull();
        ResourcesEntity resources = new ResourcesEntity();
        resources.setResourceId(1l);
        resources.setResourceName("请选择");
        roots.add(0, resources);
        
        return roots;
    }
	
	@PostMapping({"/save", "/update"})
    @ResponseBody
    @Transactional
    public JsonResult form(@Valid ResourcesEntity resources) {
        try {
        	resDao.save(resources);
        	return JsonResult.success();
		} catch (Exception e) {
			return JsonResult.error("校验不通过！");
		}
    }
	
	/**

	 * 删除权限

	 * @param id

	 * @return

	 */
	@GetMapping("/delete")
    @ResponseBody
    @Transactional
    public JsonResult delete(Long id) {
        try {
			// 先删除角色-权限中间表

        	resMapper.deleteByResourceId(id);
        	ResourcesEntity resources = resDao.findOne(id);
			if (resources != null) {
				resDao.delete(resources);
			}
			return JsonResult.success();
		} catch (Exception e) {
			return JsonResult.error(e.getMessage());
		}
    }
	
}

